package com.yfore.jfinal.pdf.plugin;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Proxy;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.jfinal.render.RenderManager;

/**
 * PDF工具类
 * @author farmer
 *
 */
public class PdfKit {

	static ITextRenderer iTextRenderer = null;
	
	/**
	 * 
	 * @param mainRenderFactory
	 * @param iTextRenderer
	 */
	static void init(ITextRenderer iTextRenderer){
		PdfKit.iTextRenderer = iTextRenderer;
	}
	
	
	/**
	 * 
	 * @param out
	 * 	pdf输出流
	 * @param html
	 * 	页面
	 * @throws PdfCreateException
	 */
	public static void createPdf(OutputStream out, String html) throws PdfCreateException{
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(new ByteArrayInputStream(html.getBytes("UTF-8")));
			iTextRenderer.setDocument(doc, null);
			iTextRenderer.layout();
			iTextRenderer.createPDF(out);
		} catch (Exception e) {
			throw new PdfCreateException("创建PDF错误	！",e);
		} finally {
			if (out != null){
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 创建pdf,并将paf输出到out流
	 * @param out
	 * 	pdf输出流
	 * @param viewPath
	 * 	pdf模板路径
	 * @param dataMap
	 * 	模板变量
	 * @throws PdfCreateException 
	 * 	创建异常
	 */
	public static void createPdf(OutputStream out, String viewPath ,Map<String, Object> dataMap) throws PdfCreateException{
		PrintWriter writer = null;
		try {
	        HttpServletResponse response = (HttpServletResponse) Proxy.newProxyInstance(
	        		PdfKit.class.getClassLoader(), new Class[]{HttpServletResponse.class}, new MockHttpServletResponse());
	        HttpServletRequest request = (HttpServletRequest) Proxy.newProxyInstance(
	        		PdfKit.class.getClassLoader(), new Class[]{HttpServletRequest.class}, new MockHttpServletRequest());
	        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
		        request.setAttribute(entry.getKey(), entry.getValue());
			}
	        RenderManager.me().getRenderFactory().getRender(viewPath).setContext(request, response).render();
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(new ByteArrayInputStream(response.getWriter().toString().getBytes("UTF-8")));
			iTextRenderer.setDocument(doc, null);
			iTextRenderer.layout();
			iTextRenderer.createPDF(out);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PdfCreateException(e);
		} finally {
            if (writer != null) {
                writer.close();
            }
			if (out != null){
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}